package com.linmo.personalcenter;

import com.linmo.loginmanage.UserManage;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ChangePasswordDialog extends JDialog {
    private JPasswordField currentPasswordField;
    private JPasswordField newPasswordField;
    private JPasswordField confirmPasswordField;
    private JButton changePasswordButton;
    private JButton cancelButton;
    private UserManage userManage;

    public ChangePasswordDialog(int userId,JFrame mainFrame) {
        super(mainFrame, "修改密码", true);
        setSize(300, 200);
        setLocationRelativeTo(mainFrame);
        setLayout(new BorderLayout());
        setResizable(false);

        // 创建面板
        JPanel panel = new JPanel(new GridLayout(4, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JLabel currentPasswordLabel = new JLabel("当前密码:");
        currentPasswordField = new JPasswordField();
        JLabel newPasswordLabel = new JLabel("新密码:");
        newPasswordField = new JPasswordField();
        JLabel confirmPasswordLabel = new JLabel("确认新密码:");
        confirmPasswordField = new JPasswordField();

        panel.add(currentPasswordLabel);
        panel.add(currentPasswordField);
        panel.add(newPasswordLabel);
        panel.add(newPasswordField);
        panel.add(confirmPasswordLabel);
        panel.add(confirmPasswordField);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        changePasswordButton = new JButton("修改密码");
        cancelButton = new JButton("取消");

        buttonPanel.add(changePasswordButton);
        buttonPanel.add(cancelButton);

        // 添加动作监听器
        changePasswordButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String currentPassword = new String(currentPasswordField.getPassword());
                String newPassword = new String(newPasswordField.getPassword());
                String confirmPassword = new String(confirmPasswordField.getPassword());

                if (newPassword.equals(confirmPassword)) {
                    // 调用用户管理模块的修改密码方法
                    UserManage.changePassword(userId, currentPassword, newPassword);
                    JOptionPane.showMessageDialog(ChangePasswordDialog.this, "密码修改成功");
                    dispose();
                } else {
                    JOptionPane.showMessageDialog(ChangePasswordDialog.this, "新密码和确认密码不一致", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });

        // 添加到主面板
        add(panel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }
}
